package org.graduation.gateway;

import io.netty.util.internal.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.graduation.gateway.properties.WhiteOrderProperties;
import org.graduation.utils.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;

@Component
public class AuthorizeFilter implements GlobalFilter {
    @Autowired
    private WhiteOrderProperties whiteOrderProperties;

    @Autowired
    private Token tokenTool;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        if (whiteOrderProperties.getOrder().contains(request.getURI().getPath())) {
            return chain.filter(exchange);
        }
        String auth = request.getHeaders().getFirst("authorization");
        if (StringUtils.isEmpty(auth) && Objects.equals(request.getMethod(), HttpMethod.GET)) {
            // 尝试从GET请求中获取token
            auth = request.getQueryParams().getFirst("auth");
        }
        if (verifyToken(auth)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        } else {
            return chain.filter(exchange);
        }
    }


    protected boolean verifyToken(String token) {
        return StringUtil.isNullOrEmpty(token) && !tokenTool.verifyToken(token);
    }
}
